// src/pages/ProjectDetail.jsx
import React, { useState, useMemo, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { demoProject } from '../../data/projects';
import TechCategory from '../../components/TechCategory';
import { Timeline, Tag, Collapse, Table, Tabs, Button, Tooltip, message } from 'antd';
import { EditOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import MarkdownEditor from '../../components/MarkdownEditor';
// import 'antd/es/timeline/style/css';
// import 'antd/es/tag/style/css';

const { Panel: CollapsePanel } = Collapse;

export default function ProjectDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [project, setProject] = useState(demoProject);
  const [isEditing, setIsEditing] = useState(false);
  const [editStates, setEditStates] = useState({
    config: false,
    version: false,
    document: false,
    task: false,
    tech: false,
    progress: false
  });
  
  // 切换编辑模式
  const toggleEdit = () => {
    setIsEditing(!isEditing);
  };
  
  // 切换模块编辑状态
  const toggleModuleEdit = (module) => {
    setEditStates(prev => ({
      ...prev,
      [module]: !prev[module]
    }));
  };
  
  // 保存模块编辑
  const saveModuleEdit = (module) => {
    // 这里可以添加保存逻辑
    console.log(`保存${module}的修改`);
    setEditStates(prev => ({
      ...prev,
      [module]: false
    }));
  };
  
  // 取消模块编辑
  const cancelModuleEdit = (module) => {
    setEditStates(prev => ({
      ...prev,
      [module]: false
    }));
  }; 
  
  // 渲染模块编辑按钮
  const renderModuleEditButton = (module) => {
    if (!isEditing) return null;
    
    if (editStates[module]) {
      return (
        <div className="module-edit-buttons">
          <Tooltip title="保存">
            <Button 
              type="text" 
              icon={<CheckOutlined />} 
              onClick={() => saveModuleEdit(module)}
              size="small"
            />
          </Tooltip>
          <Tooltip title="取消">
            <Button 
              type="text" 
              icon={<CloseOutlined />} 
              onClick={() => cancelModuleEdit(module)}
              size="small"
              danger
            />
          </Tooltip>
        </div>
      );
    } else {
      return (
        <Tooltip title="编辑">
          <Button 
            type="text" 
            icon={<EditOutlined />} 
            onClick={() => toggleModuleEdit(module)}
            className="edit-button"
            size="small"
          />
        </Tooltip>
      );
    }
  };
  const hasPublishPermission = true; // 是否有发布历史权限
  const hasTaskPermission = true; // 是否有任务历史权限
  const hasTechPermission = true; // 是否有技术栈权限
  const hasConfigPermission = true; // 是否有配置信息权限
  const hasTaskDetailsPermission = true; // 是否有任务详情权限
  const hasDocumentPermission = true; // 是否有项目文档权限
  
  // 添加状态来控制中间区域显示的内容（文档/任务详情）
  const [activeTab, setActiveTab] = useState('document'); // 默认显示项目文档
  
  // 点击新增版本按钮的处理函数
  const handleAddVersion = () => {
    navigate(`/project/${id}/add-version`);
  };

  
  const renderVersionHistory = () => (
    <div className="version-list">
      <div className="version-header-actions">
        <button 
          className="btn-add-version" 
          onClick={handleAddVersion}
        >
          新增版本
        </button>
      </div>
      {project.versions?.map((v) => (
        <div key={v.number} className="version-item">
          <div className="version-header">
            <span className="version-tag">v{v.number}</span>
            <span className="update-time">{v.date}</span>
          </div>
          <CollapsePanel title="更新详情">
            <ul className="update-details">
              {v.changes.map((change, i) => (
                <li key={i}>{change}</li>
              ))}
            </ul>
          </CollapsePanel>
        </div>
      ))}
    </div>
  );

  const renderTaskProgress = () => (
    <div className="task-timeline">
    {project.tasks?.map((task, index) => (
      <React.Fragment key={task.id}>
        <div className="task-item">
          <div className="task-header">
            <span className="task-name">{task.name}</span>
            <span className={`task-status ${task.progress === 100 ? 'completed' : ''}`}>
              {task.status}
            </span>
          </div>
          {task.progress < 100 && (
            <div className="progress-container">
              <div 
                className="progress-bar"
                style={{ width: `${task.progress}%` }}
              />
              <span className="progress-text">{task.progress}%</span>
            </div>
          )}
          <div className="task-meta">
            <span>产品经理：{task.pm}</span>
            <span>截止时间：{task.deadline}</span>
          </div>
        </div>
        {index < project.tasks.length - 1 && (
          <hr className="task-divider" />
        )}
      </React.Fragment>
    ))}
  </div>
  );

  // 保存文档内容
  const handleSaveDocument = useCallback(async (content) => {
    try {
      const response = await fetch(`/api/project/update`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          id: parseInt(id),
          projectDoc: content,
          updateTime: new Date().toISOString()
        }),
      });

      const result = await response.json();
      if (result.code === '200' || result.success) {
        // 更新本地项目数据
        setProject(prev => ({
          ...prev,
          projectDoc: content,
          updateTime: new Date().toISOString()
        }));
        message.success('文档保存成功');
        return true;
      } else {
        message.error(result.message || '保存失败');
        return false;
      }
    } catch (error) {
      console.error('保存文档失败:', error);
      message.error('保存失败，请稍后重试');
      return false;
    }
  }, [id]);

  // 新增项目文档渲染函数
  const renderProjectDocuments = (isEditing) => {
    if (isEditing) {
      return (
        <MarkdownEditor 
          initialContent={project.projectDoc || '#'}
          onSave={handleSaveDocument}
        />
      );
    }
    
    if (project.projectDoc) {
      return (
        <div className="markdown-preview">
          <MDEditor.Markdown 
            source={project.projectDoc} 
            style={{ whiteSpace: 'pre-wrap' }} 
          />
        </div>
      );
    }
    
    return (
      <div className="project-documents">
        <div className="document-list">
          {project.documents ? (
            project.documents.map((doc, index) => (
              <div key={index} className="document-item">
                <div className="document-icon">
                  {doc.type === 'pdf' && <i className="document-icon-pdf">PDF</i>}
                  {doc.type === 'doc' && <i className="document-icon-word">DOC</i>}
                  {doc.type === 'xls' && <i className="document-icon-excel">XLS</i>}
                </div>
                <div className="document-info">
                  <div className="document-name">{doc.name}</div>
                  <div className="document-meta">
                    <span>上传人: {doc.uploader}</span>
                    <span>上传时间: {doc.uploadTime}</span>
                    <span>文件大小: {doc.size}</span>
                  </div>
                </div>
                <div className="document-actions">
                  <button className="btn-view">查看</button>
                  <button className="btn-download">下载</button>
                </div>
              </div>
            ))
          ) : (
            <div className="no-documents">
              <p>暂无项目文档</p>
              <button className="btn-upload">上传文档</button>
            </div>
          )}
        </div>
        
        <div className="upload-section">
          <button className="btn-upload-new">上传新文档</button>
        </div>
      </div>
    );
  };

  // 任务详情渲染函数
  const renderTaskDetails = () => (
    <div className="task-details">
      <Table
        dataSource={project.tasks || []}
        rowKey="id"
        pagination={false}
        className="task-details-table"
        columns={[
          {
            title: '任务名称',
            dataIndex: 'name',
            key: 'name',
            width: 150,
          },
          {
            title: '任务详情',
            dataIndex: 'description',
            key: 'description',
            width: 200,
            render: (text) => text || '-'
          },
          {
            title: '开始时间',
            dataIndex: 'startDate',
            key: 'startDate',
            width: 120,
            render: (text) => text || '-'
          },
          {
            title: '结束时间',
            dataIndex: 'deadline',
            key: 'deadline',
            width: 120,
          },
          {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            width: 100,
            render: (text) => (
              <Tag color={text === '需求' ? 'blue' : 'red'}>
                {text || '需求'}
              </Tag>
            )
          },
          {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 100,
            render: (status) => {
              let color = 'default';
              if (status === '已完成') color = 'green';
              else if (status === '测试中') color = 'purple';
              else if (status === '开发中') color = 'blue';
              else if (status === '未开始') color = 'orange';
              
              return (
                <Tag color={color}>
                  {status}
                </Tag>
              );
            }
          },
        ]}
      />
    </div>
  );

  const renderTechStack = () => (
    <div className="tech-stack">
      <TechCategory 
        title="第三方平台" 
        items={project.techStack?.platforms}
        badgeClass="platform-badge"
      />
      <TechCategory
        title="SDK集成"
        items={project.techStack?.sdks}
        badgeClass="sdk-badge"
      />
      <TechCategory
        title="基础框架"
        items={project.techStack?.frameworks}
        badgeClass="framework-badge"
      />
    </div>
  );
  const renderConfigInfo = () => (
    <table className="config-table">
      <tbody>
        <tr>
          <td className="config-label">Gradle版本</td>
          <td className="config-value">{project.config?.gradle}</td>
        </tr>
        <tr>
          <td>Java SDK</td>
          <td>{project.config?.java}</td>
        </tr>
        <tr>
          <td>Kotlin版本</td>
          <td>{project.config?.kotlin}</td>
        </tr>
        <tr>
          <td>构建工具</td>
          <td>{project.config?.buildTools}</td>
        </tr>
        <tr>
          <td>最低SDK</td>
          <td>API {project.config?.minSdk}</td>
        </tr>
        <tr>
          <td>目标SDK</td>
          <td>API {project.config?.targetSdk}</td>
        </tr>
      </tbody>
    </table>
  );

  const VersionTimeline = ({ versions }) => (
    <section className="version-history">
      <h3>版本发布历史</h3>
      <Timeline mode="alternate">
        {versions?.map((v, i) => (
          <Timeline.Item
            key={i}
            label={v.date}
            color={v.status === 'beta' ? 'orange' : 'green'}
          >
            <div className="version-card">
              <div className="version-header">
                <Tag color={getVersionColor(v.type)}>{v.version}</Tag>
                <span className="version-type">{v.type}</span>
              </div>
              <ul className="highlights">
                {v.highlights.map((h, j) => (
                  <li key={j}>{h}</li>
                ))}
              </ul>
            </div>
          </Timeline.Item>
        ))}
      </Timeline>
    </section>
  );

  const getVersionColor = (type) => {
    switch(type) {
      case 'feature': return 'green';
      case 'patch': return 'blue';
      default: return 'gray';
    }
  };

  const SectionModule = React.memo(({ title, visible, content, className, moduleId }) => {
    if (!visible) return null;
    
    // 使用useMemo优化渲染
    const renderedContent = useMemo(() => {
      return content(editStates[moduleId]);
    }, [content, editStates, moduleId]);
    
    // 使用useMemo缓存编辑按钮
    const editButton = useMemo(() => {
      return renderModuleEditButton(moduleId);
    }, [moduleId, isEditing, editStates]);
    
    return (
      <div className={`section-module ${className}`}>
        <div className="module-header">
          <h3>{title}</h3>
          {editButton}
        </div>
        {renderedContent}
      </div>
    );
  });

  return (
    <div className="project-detail">
    {/* 基础信息区块 */}
    <div className="base-info">
      <div className="base-info-header">
        <h2>{project.name}</h2>
        <Button 
          type={isEditing ? 'primary' : 'default'}
          icon={<EditOutlined />}
          onClick={toggleEdit}
          className="edit-toggle-button"
        >
          {isEditing ? '退出编辑' : '编辑'}
        </Button>
      </div>
      <p className="project-status">
        状态：{project.status}
      </p>
    </div>

    {/* 信息模块容器 */}
    <div className="info-modules">
      {/* 左侧上下布局 */}
      <div className="left-column">
        <SectionModule
          title="项目配置详情"
          visible={hasConfigPermission}
          content={renderConfigInfo}
          className="config-section"
          moduleId="config"
        />
        <SectionModule
          title="版本发布历史"
          visible={hasPublishPermission}
          content={renderVersionHistory}
          className="version-section"
          moduleId="version"
        />
        {/* <VersionTimeline versions={project.versionHistory} /> */}
      </div>

      {/* 中间主区域 */}
      <div className="center-column">
        <div className="tab-buttons">
          <button 
            className={`tab-button ${activeTab === 'document' ? 'active' : ''}`}
            onClick={() => setActiveTab('document')}
          >
            项目文档
          </button>
          <button 
            className={`tab-button ${activeTab === 'task' ? 'active' : ''}`}
            onClick={() => setActiveTab('task')}
          >
            任务详情
          </button>
        </div>
        
        {activeTab === 'document' && hasDocumentPermission && (
          <SectionModule
            title="项目文档"
            visible={true}
            content={renderProjectDocuments}
            className="document-section"
            moduleId="document"
          />
        )}
        
        {activeTab === 'task' && hasTaskDetailsPermission && (
          <SectionModule
            title="任务详情"
            visible={true}
            content={renderTaskDetails}
            className="task-details-section"
            moduleId="task"
          />
        )}
      </div>

      {/* 右侧区域 - 技术组件清单和任务进度跟踪的上下布局 */}
      <div className="right-column">
        {/* 技术组件清单模块（上方，占高度的三分之一） */}
        <SectionModule
          title="技术组件清单"
          visible={hasTechPermission}
          content={renderTechStack}
          className="tech-section"
          moduleId="tech"
        />
        
        {/* 任务进度跟踪模块（下方，占高度的三分之二） */}
        <SectionModule
          title="任务进度跟踪"
          visible={hasTaskPermission}
          content={renderTaskProgress}
          className="task-section"
          moduleId="progress"
        />
      </div>
    </div>
    <style>
      {`
        .right-column {
          display: flex;
          flex-direction: column;
          gap: 24px;
          height: 100%;
        }
        
        .tech-section {
          flex: 1;
          height: calc(100% * 1/3) !important;
          min-height: unset !important;
          overflow-y: auto;
        }
        
        .task-section {
          flex: 2;
          height: calc(100% * 2/3) !important;
          min-height: unset !important;
          overflow-y: auto;
        }
        
        /* 新增版本按钮样式 */
        /* 模块头部样式 */
        .module-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
        }
        
        .edit-button {
          color: #999;
          opacity: 0.7;
          transition: all 0.3s;
        }
        
        .edit-button:hover {
          color: #1890ff;
          opacity: 1;
        }
        
        .module-edit-buttons {
          display: flex;
          gap: 4px;
        }
        
        .base-info-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
        
        .edit-toggle-button {
          margin-left: 16px;
        }
        
        .version-header-actions {
          display: flex;
          justify-content: flex-end;
          margin-bottom: 16px;
        }
        
        .btn-add-version {
          background-color: #1890ff;
          color: white;
          border: none;
          border-radius: 4px;
          padding: 8px 16px;
          cursor: pointer;
          font-size: 14px;
          display: flex;
          align-items: center;
          transition: all 0.3s;
        }
        
        .btn-add-version:hover {
          background-color: #40a9ff;
          box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
        }
        
        /* 中间区域样式 */
        .center-column {
          display: flex;
          flex-direction: column;
          width: 100%;
        }
        
        /* 切换按钮样式 */
        .tab-buttons {
          display: flex;
          margin-bottom: 16px;
          border-bottom: 1px solid #e8e8e8;
        }
        
        .tab-button {
          padding: 8px 16px;
          margin-right: 8px;
          background: none;
          border: none;
          cursor: pointer;
          font-size: 14px;
          position: relative;
          color: #666;
        }
        
        .tab-button.active {
          color: #1890ff;
          font-weight: 500;
        }
        
        .tab-button.active::after {
          content: '';
          position: absolute;
          bottom: -1px;
          left: 0;
          width: 100%;
          height: 2px;
          background-color: #1890ff;
        }
        
        /* 项目文档样式 */
        .project-documents {
          padding: 16px;
        }
        
        .document-list {
          margin-bottom: 24px;
        }
        
        .document-item {
          display: flex;
          padding: 16px;
          border: 1px solid #e8e8e8;
          border-radius: 4px;
          margin-bottom: 12px;
          align-items: center;
        }
        
        .document-icon {
          width: 40px;
          height: 40px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16px;
          border-radius: 4px;
          font-weight: bold;
        }
        
        .document-icon-pdf {
          background-color: #ff4d4f;
          color: white;
          padding: 4px 8px;
          border-radius: 4px;
        }
        
        .document-icon-word {
          background-color: #1890ff;
          color: white;
          padding: 4px 8px;
          border-radius: 4px;
        }
        
        .document-icon-excel {
          background-color: #52c41a;
          color: white;
          padding: 4px 8px;
          border-radius: 4px;
        }
        
        .document-info {
          flex: 1;
        }
        
        .document-name {
          font-weight: 500;
          margin-bottom: 8px;
        }
        
        .document-meta {
          display: flex;
          color: #999;
          font-size: 12px;
        }
        
        .document-meta span {
          margin-right: 16px;
        }
        
        .document-actions {
          display: flex;
        }
        
        .document-actions button {
          margin-left: 8px;
          padding: 4px 12px;
          border: 1px solid #d9d9d9;
          border-radius: 4px;
          background: white;
          cursor: pointer;
        }
        
        .btn-view {
          color: #1890ff;
        }
        
        .btn-download {
          color: #52c41a;
        }
        
        .btn-upload, .btn-upload-new {
          padding: 8px 16px;
          background-color: #1890ff;
          color: white;
          border: none;
          border-radius: 4px;
          cursor: pointer;
        }
        
        .no-documents {
          text-align: center;
          padding: 32px;
          color: #999;
        }
        
        .no-documents p {
          margin-bottom: 16px;
        }
        
        .upload-section {
          display: flex;
          justify-content: flex-end;
        }
      `}
    </style>
  </div>
  );
}